package com.amado.course42Nio.demo2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/7 0:00
 */
public class NioServer2 {
    private Selector selector;
    public static void main(String[] args) throws IOException {
        NioServer2 nioServer = new NioServer2();
        nioServer.go();
    }

    NioServer2() throws IOException {
        ServerSocketChannel channel = ServerSocketChannel.open();
        //默认是true,false不堵塞
        channel.configureBlocking(false);
        ServerSocket socket = channel.socket();
        socket.bind(new InetSocketAddress(8080));
        selector = Selector.open();
        // 绑定channel的accept
        channel.register(selector, SelectionKey.OP_ACCEPT);
    }

    private void go() throws IOException {
        while (selector.select() > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isAcceptable()) {
                    accept(selectionKey);
                } else if (selectionKey.isReadable()) {
                    read(selectionKey);
                }
            }
        }
    }

    private void accept(SelectionKey selectionKey) throws IOException {
        ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
        SocketChannel socketChannel = server.accept();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector,SelectionKey.OP_READ);
        System.out.println("acceptable");
    }
    private void read(SelectionKey selectionKey) throws IOException {
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
        socketChannel.read(readBuffer);
        readBuffer.flip();
        CharBuffer charBuffer = Charset.forName("UTF-8").decode(readBuffer);
        System.out.println("接收到数据 " + charBuffer.array());
        System.out.println("接收到数据 " + new String(charBuffer.array()));
        //重新读取
        readBuffer.rewind();
        writeBuffer.put("echo from client".getBytes("UTF-8"));
        writeBuffer.put(readBuffer);
        writeBuffer.flip();
        socketChannel.write(writeBuffer);
        readBuffer.clear();
    }
}
